<?php
abstract class App_Service_Abstract 
{
    protected $_mapper;
    
    protected $_entity = null;
    
    protected $_form;
    
    public function __construct($mapper = null)
    {
        if($mapper !== null){
            $this->_mapper = $mapper;
        }
        $this->init();

    }
    /*
     * init hook
     */
    public function init(){}
    
    /*
     * getters and setters
     */
    public function setForm($form)
    {
        $this->_form = $form;
    }
    
    public function getForm()
    {
        return $this->_form;
    }
    
    public function setMapper($mapper)
    {
        $this->_mapper = $mapper;
    }
    
    public function getMapper()
    {
        return $this->_mapper;
    }
    
    public function setEntity($entity)
    {
        $this->_entity = $entity;
        if($this->_form){
	        $formClassName = get_class($this->_form);
	        $this->setForm(new $formClassName($this->_entity));
        }
    }
    
    public function getEntity()
    {
        return $this->_entity;
    }
    
    /*
     * load domain object by id
     * @param $entityId (integer)
     * @param $options array
     */
    public function loadEntity($entityId, array $options = null)
    {
        if(!$entityId){
            return false;
        }
        $this->setEntity($this->_mapper->load((int) $entityId, $options));
        return $this->getEntity();
    }
    
    public function save(array $data, $id = null)
    {
    	
        if(!$this->_form->isValid($data)){
            return false;
        }
   
        $entityName = $this->_mapper->getEntityClassName();
        $this->_entity = new $entityName($this->_form->getValues());
        if($id !==null){
            $this->_entity->id = $id;
        }
        return $this->_mapper->save($this->_entity);
    }
    
    public function delete($entity = null)
    {
        if($entity === null){
            if($this->_entity === null){
                throw new Exception('Entity dosent exists for delete action');
            }
            $this->_mapper->delete($this->_entity);
        } else {
            $this->_mapper->delete($entity);
        }    
        $this->_entity = null;
    }
    
    public function clearEntity()
    {
        $this->setEntity(null);
    }
    
    public function getAll()
    {
    	return $this->_mapper->getAll();
    }
}